var SERVER_URL = 'http://103.224.249.202/api/'
var LOGIN_URL = SERVER_URL + 'login';
var LOGOUT_URL = SERVER_URL + 'logout';
var GETUSER_URL = SERVER_URL + 'get_user_info';
var SETUSER_URL = SERVER_URL + "set_user";
var GETTASK_URL = SERVER_URL + "get_task";
var ADDTASK_URL = SERVER_URL + "add_task";
var gUserName = "";

function isValidUser() {
	if (gUserName != null && gUserName.length > 0) {
		return true;
	}
	return false;
}

function user_init(callback, errCallback) {
	var skey = $.cookie("hurricane.skey");
	//var skey = "a8e24c54-4b70-11e4-9b3d-5e8cf9ab6ddc";
	if (skey == "null" || skey == null || skey.length == 0) {
		skey = null;
		errCallback();
	} else {
		var params = "skey=" + skey;
		//var btn_oauth = $('div.yk-toolbar-oauth-login').find('button');
		$.ajax({
			url: GETUSER_URL,
			data: params,
			type: "get",
			dataType: "json",
			success: function(data){
				if (data.code == 200) {
					gUserName = data.data[0].username;
					callback(gUserName);
				} else
					errCallback();
			},
			error: function(xhr, data) {
				errCallback();
			}
		});
	}
}

function user_logout(callback) {
	var skey = $.cookie("hurricane.skey");
	//var skey = "a8e24c54-4b70-11e4-9b3d-5e8cf9ab6ddc";
	var params = "skey=" + skey;
	$.getJSON(LOGOUT_URL, params, function() {
		gUserName = "";
		$.cookie("hurricane.skey", null, {path:"/"});
		callback();
	});
}

function user_login(username, password, callback, errCallback) {
	var params = 'username=' + username + '&password=' + password;
	$.ajax({
		url: LOGIN_URL, 
		data: params, 
		type: "post",
		dataType: "json",
		success: function(data) {
			if (data.code != 200) {
				errCallback(data.message);
			} else {
				skey = data['data'][0].skey;
				if (skey != null) {
					$.cookie("hurricane.skey", skey, {path:"/"});
				}
				callback();
			}
		},
		error: function(xhr, data) {
			errCallback(data);
		},
	});
}

function user_register(username, password, callback, errCallback) {
	var params = 'action=add&data={"username": "' + username + '", "password": "' + password + '"}';
	$.ajax({
		url: SETUSER_URL, 
		data: params, 
		type: "post",
		dataType: "json",
		success: function(data) {
			if (data.code != 200) {
				errCallback(data.message);
			} else {
				callback();
			}
		},
		error: function(xhr, data) {
			errCallback(data);
		},
	});
}